package model

import (
	"sort"

	"file_explorer/common/util"
)

const (
	ConfKeyFavoritesNotExist = "favorites_not_exist"
	ConfKeyShowVirtualFile   = "show_virtual_file"
	ConfKeyMetaFileNum       = "meta_file_num"
	ConfKeyLogRowNum         = "log_row_num"
	ConfKeyFavorites         = "favorites"
)

type Favorites struct {
	Path string `yaml:"path"`
	Name string `yaml:"name"`
}

type GlobalConf struct {
	FavoritesNotExist string       `yaml:"favorites_not_exist"`
	ShowVirtualFile   bool         `yaml:"show_virtual_file"`
	MetaFileNum       int          `yaml:"meta_file_num"`
	LogRowNum         int          `yaml:"log_row_num"`
	Favorites         []*Favorites `yaml:"favorites,omitempty"`
}

func (conf *GlobalConf) SetConfByKey(key string, value interface{}) {
	switch key {
	case ConfKeyFavoritesNotExist:
		conf.FavoritesNotExist = value.(string)
	case ConfKeyShowVirtualFile:
		conf.ShowVirtualFile = value.(bool)
	case ConfKeyMetaFileNum:
		conf.MetaFileNum = value.(int)
	case ConfKeyLogRowNum:
		conf.LogRowNum = value.(int)
	case ConfKeyFavorites:
		if value == nil {
			conf.Favorites = nil
		} else {
			conf.Favorites = value.([]*Favorites)
		}
	}
}

func (conf *GlobalConf) AddFavorites(path string, name string) {
	if conf.Favorites == nil {
		conf.Favorites = make([]*Favorites, 0)
	}

	conf.Favorites = append(conf.Favorites, &Favorites{
		Path: path,
		Name: name,
	})

	sort.Slice(conf.Favorites, func(i, j int) bool {
		return util.CmpText(conf.Favorites[i].Name, conf.Favorites[j].Name) > 0
	})
}

func (conf *GlobalConf) DeleteFavorites(path string) {
	index := conf.FindFavorites(path)
	if index < 0 {
		return
	}
	newFavorites := conf.Favorites[:index]
	if index+1 < len(conf.Favorites) {
		newFavorites = append(newFavorites, conf.Favorites[index+1:]...)
	}
	conf.Favorites = newFavorites
}

func (conf *GlobalConf) FindFavorites(path string) int {
	for index, favorites := range conf.Favorites {
		if favorites.Path == path {
			return index
		}
	}
	return -1
}
